﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Mail;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace YTCMS.Core
{
    /// <summary>
    /// 应用全局类
    /// </summary>
    public static class Globals
    {

        ///   <summary>   
        ///   按字符串实际长度截取定长字符窜   
        ///   </summary>   
        ///   <param   name="str">原字符串</param>   
        ///   <param   name="length">要截取的长度</param>   
        ///   <returns>string型字符串</returns>   
        public static string TitleSubstring(string str, int length)
        {
            int i = 0, j = 0;
            foreach (char chr in str)
            {
                if ((int)chr > 127)
                {
                    i += 2;
                }
                else
                {
                    i++;
                }
                if (i > length)
                {
                    str = str.Substring(0, j) + "...";
                    break;
                }
                j++;
            }
            return str;

        }

        /// <summary>
        /// IP地址
        /// </summary>
        public static string IPAddress
        {
            get
            {
                HttpRequest request = HttpContext.Current.Request;
                string text;
                if (string.IsNullOrEmpty(request.ServerVariables["HTTP_X_FORWARDED_FOR"]))
                {
                    text = request.ServerVariables["REMOTE_ADDR"];
                }
                else
                {
                    text = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                }
                if (string.IsNullOrEmpty(text))
                {
                    text = request.UserHostAddress;
                }
                return text;
            }
        }
        /// <summary>
        /// 虚拟根路径
        /// </summary>
        public static string ApplicationPath
        {
            get
            {
                string text = "/";
                if (HttpContext.Current != null)
                {
                    text = HttpContext.Current.Request.ApplicationPath;
                }
                string result;
                if (text == "/")
                {
                    result = string.Empty;
                }
                else
                {
                    result = text.ToLower(CultureInfo.InvariantCulture);
                }
                return result;
            }
        }
        /// <summary>
        /// 域名
        /// </summary>
        public static string DomainName
        {
            get
            {
                string result;
                if (HttpContext.Current == null)
                {
                    result = string.Empty;
                }
                else
                {
                    result = HttpContext.Current.Request.Url.Host;
                }
                return result;
            }
        }
        public static void RedirectToSSL(HttpContext context)
        {
            if (null != context)
            {
                if (!context.Request.IsSecureConnection)
                {
                    Uri url = context.Request.Url;
                    context.Response.Redirect("https://" + url.ToString().Substring(7));
                }
            }
        }
        public static string AppendQuerystring(string url, string querystring)
        {
            return Globals.AppendQuerystring(url, querystring, false);
        }
        public static string AppendQuerystring(string url, string querystring, bool urlEncoded)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            string str = "?";
            if (url.IndexOf('?') > -1)
            {
                if (!urlEncoded)
                {
                    str = "&";
                }
                else
                {
                    str = "&amp;";
                }
            }
            return url + str + querystring;
        }
        public static string HtmlDecode(string textToFormat)
        {
            string result;
            if (string.IsNullOrEmpty(textToFormat))
            {
                result = textToFormat;
            }
            else
            {
                result = HttpUtility.HtmlDecode(textToFormat);
            }
            return result;
        }
        public static string HtmlEncode(string textToFormat)
        {
            string result;
            if (string.IsNullOrEmpty(textToFormat))
            {
                result = textToFormat;
            }
            else
            {
                result = HttpUtility.HtmlEncode(textToFormat);
            }
            return result;
        }
        public static string UrlEncode(string urlToEncode)
        {
            string result;
            if (string.IsNullOrEmpty(urlToEncode))
            {
                result = urlToEncode;
            }
            else
            {
                result = HttpUtility.UrlEncode(urlToEncode, Encoding.UTF8);
            }
            return result;
        }
        public static string UrlDecode(string urlToDecode)
        {
            string result;
            if (string.IsNullOrEmpty(urlToDecode))
            {
                result = urlToDecode;
            }
            else
            {
                result = HttpUtility.UrlDecode(urlToDecode, Encoding.UTF8);
            }
            return result;
        }
        public static string StripScriptTags(string content)
        {
            content = Regex.Replace(content, "<script((.|\n)*?)</script>", "", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            content = Regex.Replace(content, "'javascript:", "", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            return Regex.Replace(content, "\"javascript:", "", RegexOptions.IgnoreCase | RegexOptions.Multiline);
        }
        public static string StripAllTags(string strToStrip)
        {
            strToStrip = Regex.Replace(strToStrip, "</p(?:\\s*)>(?:\\s*)<p(?:\\s*)>", "\n\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            strToStrip = Regex.Replace(strToStrip, "<br(?:\\s*)/>", "\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            strToStrip = Regex.Replace(strToStrip, "\"", "''", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            strToStrip = Globals.StripHtmlXmlTags(strToStrip);
            return strToStrip;
        }
        public static string StripHtmlXmlTags(string content)
        {
            return Regex.Replace(content, "<[^>]+>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        }
        public static string HostPath(Uri uri)
        {
            string result;
            if (uri == null)
            {
                result = string.Empty;
            }
            else
            {
                string text = (uri.Port == 80) ? string.Empty : (":" + uri.Port.ToString(CultureInfo.InvariantCulture));
                result = string.Format(CultureInfo.InvariantCulture, "{0}://{1}{2}", new object[]
				{
					uri.Scheme,
					uri.Host,
					text
				});
            }
            return result;
        }
        public static string FullPath(string local)
        {
            string result;
            if (string.IsNullOrEmpty(local))
            {
                result = local;
            }
            else
            {
                if (local.ToLower(CultureInfo.InvariantCulture).StartsWith("http://"))
                {
                    result = local;
                }
                else
                {
                    if (HttpContext.Current == null)
                    {
                        result = local;
                    }
                    else
                    {
                        result = Globals.FullPath(Globals.HostPath(HttpContext.Current.Request.Url), local);
                    }
                }
            }
            return result;
        }
        public static string FullPath(string hostPath, string local)
        {
            return hostPath + local;
        }
        public static string UnHtmlEncode(string formattedPost)
        {
            RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled;
            formattedPost = Regex.Replace(formattedPost, "&quot;", "\"", options);
            formattedPost = Regex.Replace(formattedPost, "&lt;", "<", options);
            formattedPost = Regex.Replace(formattedPost, "&gt;", ">", options);
            return formattedPost;
        }
        public static string StripForPreview(string content)
        {
            content = Regex.Replace(content, "<br>", "\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            content = Regex.Replace(content, "<br/>", "\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            content = Regex.Replace(content, "<br />", "\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            content = Regex.Replace(content, "<p>", "\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            content = content.Replace("'", "&#39;");
            return Globals.StripHtmlXmlTags(content);
        }
        public static string ToDelimitedString(ICollection collection, string delimiter)
        {
            string result;
            if (collection == null)
            {
                result = string.Empty;
            }
            else
            {
                StringBuilder stringBuilder = new StringBuilder();
                if (collection is Hashtable)
                {
                    foreach (object current in ((Hashtable)collection).Keys)
                    {
                        stringBuilder.Append(current.ToString() + delimiter);
                    }
                }
                if (collection is ArrayList)
                {
                    foreach (object current in (ArrayList)collection)
                    {
                        stringBuilder.Append(current.ToString() + delimiter);
                    }
                }
                if (collection is string[])
                {
                    string[] array = (string[])collection;
                    for (int i = 0; i < array.Length; i++)
                    {
                        string str = array[i];
                        stringBuilder.Append(str + delimiter);
                    }
                }
                if (collection is MailAddressCollection)
                {
                    foreach (MailAddress current2 in (MailAddressCollection)collection)
                    {
                        stringBuilder.Append(current2.Address + delimiter);
                    }
                }
                result = stringBuilder.ToString().TrimEnd(new char[]
				{
					Convert.ToChar(delimiter, CultureInfo.InvariantCulture)
				});
            }
            return result;
        }
        public static string FormatMoney(decimal money)
        {
            return string.Format(CultureInfo.InvariantCulture, "{0}", new object[]
			{
				money.ToString("F", CultureInfo.InvariantCulture)
			});
        }
        public static int[] BubbleSort(int[] r)
        {
            for (int i = 0; i < r.Length; i++)
            {
                bool flag = false;
                for (int j = r.Length - 2; j >= i; j--)
                {
                    if (r[j + 1] > r[j])
                    {
                        int num = r[j + 1];
                        r[j + 1] = r[j];
                        r[j] = num;
                        flag = true;
                    }
                }
                if (!flag)
                {
                    break;
                }
            }
            return r;
        }
        public static string GetGenerateId()
        {
            string text = string.Empty;
            Random random = new Random();
            for (int i = 0; i < 7; i++)
            {
                int num = random.Next();
                text += ((char)(48 + (ushort)(num % 10))).ToString();
            }
            return DateTime.Now.ToString("yyyyMMdd") + text;
        }
    }
}
